package com.passwd.designdecrypt.decrypt;

import com.passwd.designcore.utils.KeyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class DecryptController {

    /**
     * 接收解密请求
     * 按照规定读取路径读取文件
     * @return
     */
    @RequestMapping("decrypt")
    public static String decrypt() {
        String result = "error";
        try {
            String path = System.getProperty("user.dir");
            File dir = new File(path);
            //TODO 路径待写
            File file = new File(dir, KeyUtils.inputDecryptFileName);

            // 核心处理类
            DecryptCore core = new DecryptCore();
            result = core.decryptRun(new FileInputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
            result = e.getMessage();
        }
        return result;
    }

    /**
     * 接收加密请求
     * 上传文件形式读取文件
     *
     * @return
     */
    @RequestMapping("decryptUpload")
    public String decryptUpload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        InputStream inputStream = file.getInputStream();

        // 核心处理类
        DecryptCore core = new DecryptCore();
        String result = core.decryptRun(inputStream);
        return result;
    }
}
